package com.example.storagemodule

import android.content.ContentValues
import android.database.sqlite.SQLiteDatabase
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.Toast
import com.example.storagemodule.utils.DBHelper

class DBActivity : AppCompatActivity() {
    private val TAG = "DBActivity"
    private val name = "BookStore.db"
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_d_b)

    }

    fun testCreateDB(view: View) {
        Log.d(TAG, "testCreateDB: ")
        val dbHelper = DBHelper(this,name,1)
        dbHelper.readableDatabase
    }
    fun testUpdateDB(view: View) {
        val dbHelper = DBHelper(this,name,1)
        dbHelper
    }
    fun testInsert(view: View) {
        val dbHelper = DBHelper(this,name,1)
        val contentValue = ContentValues().apply {
            put("name","The Da Vinci Code")
            put("author","Dan Brown")
            put("pages",454)
            put("price",14.96)
        }
        val db = dbHelper.readableDatabase
        db.insert("Book",null,contentValue)

        val contentValues2 = ContentValues().apply {
            put("name","The Lost Symbols")
            put("author","Dan Brown")
            put("pages",510)
            put("price",19.95)
        }
        db.insert("Book",null,contentValues2)
    }
    fun testUpdate(view: View) {
        var dBHelper = DBHelper(this,name,1)
        val db=dBHelper.readableDatabase
        var contentValues = ContentValues().apply {
            put("price",19.99)
        }

        val no=db.update("Book",contentValues,"name = ?", arrayOf("The Da Vinci Code"))
        db.close()
        Log.d(TAG, "testUpdate: "+no)
    }
    fun testDelete(view: View) {
        var dBHelper = DBHelper(this,name,1)
        val db=dBHelper.readableDatabase
        var contentValues = ContentValues().apply {
            put("price",19.99)
        }
           val no= db.delete("Book","id = ?", arrayOf("1"))
        db.close()

        Log.d(TAG, "testUpdate: "+no)
    }
    fun testQuery(view: View) {
        var dBHelper = DBHelper(this,name,1)
        val db=dBHelper.readableDatabase
        var contentValues = ContentValues().apply {
            put("price",19.99)
        }

        val cursor=db.query("Book",null,"id = ?", arrayOf("2"),null,null,"id","0,1")
        if (cursor.moveToFirst()){
            do{
                val id=cursor.getInt(cursor.getColumnIndex("id"))
                val author=cursor.getString(cursor.getColumnIndex("author"))
                Toast.makeText(this,"id = $id, and author = $author",Toast.LENGTH_SHORT).show()
                Log.d(TAG, "id = $id, and author = $author")
            }while (cursor.moveToNext())
        }
        db.close()
    }
    fun testTransaction(view: View) {}
}